/*
 * Copyright (c) 2018. 玺得（深圳）科技有限公司.保留所有权利. http://www.pi-top.com/ 玺得（深圳）科技有限公司保留所有代码著作权.如有任何疑问请访问官方网站与我们联系. 代码只针对特定需求定制编码，不得在未经允许或授权的情况下对外传播扩散.恶意传播者，法律后果自行承担. 本代码仅用于pps-cloud系统.
 */
package com.pitop.sync.ctrl;

import com.alibaba.fastjson.JSON;
import com.pitop.core.exceptions.BaseException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

import com.pitop.core.entity.BeanRet;
import com.pitop.core.entity.Page;
import com.pitop.core.tools.redis.RedisUtils;
import com.pitop.sync.entity.SyncNewData;
import com.pitop.sync.service.SyncNewDataSV;

/**
 * 需要同步的数据 控制器
 *
 * @author pi-top
 */
@RestController
@RequestMapping("/syncNewData")
@Slf4j
@Api(value = "需要同步的数据控制器", description = "需要同步的数据控制器")
public class SyncNewDataCtrl {

    @Resource
    protected RedisUtils redisUtils;

    @Resource
    private SyncNewDataSV syncNewDataSV;

    /**
     * 查询SyncNewData一个详情信息
     *
     * @param id          id
     * @param code        编码
     * @param factoryCode 工厂编码
     * @param dataCode    数据编码
     * @return BeanRet
     */
    @ApiOperation(value = "查询SyncNewData一个详情信息", notes = "查询SyncNewData一个详情信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataType = "java.lang.Long", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "编码", dataType = "java.lang.String", paramType = "query"),
            @ApiImplicitParam(name = "factoryCode", value = "工厂编码", dataType = "java.lang.String", paramType = "query"),
            @ApiImplicitParam(name = "dataCode", value = "数据编码", dataType = "java.lang.String", paramType = "query")
    })
    @GetMapping(value = "/load")
    @ResponseBody
    public SyncNewData load(java.lang.Long id, java.lang.String code, java.lang.String factoryCode, java.lang.String dataCode) {
        if (id == null) {
            return null;
        }
        if (code == null) {
            return null;
        }
        if (factoryCode == null) {
            return null;
        }
        if (dataCode == null) {
            return null;
        }
        SyncNewData syncNewData = syncNewDataSV.load(id, code, factoryCode, dataCode);
        log.info(JSON.toJSONString(syncNewData));
        return syncNewData;
    }


    /**
     * 根据条件id查询SyncNewData一个详情信息
     *
     * @param id id
     * @return BeanRet
     */
    @ApiOperation(value = "查询SyncNewData一个详情信息", notes = "查询SyncNewData一个详情信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataType = "java.lang.Long", paramType = "path")
    })
    @GetMapping(value = "/load/id/{id}")
    @ResponseBody
    public SyncNewData loadById(@PathVariable java.lang.Long id) {
        if (id == null) {
            return null;
        }
        SyncNewData syncNewData = syncNewDataSV.loadById(id);
        log.info(JSON.toJSONString(syncNewData));
        return syncNewData;
    }

    /**
     * 根据条件code查询SyncNewData一个详情信息
     *
     * @param code 编码
     * @return BeanRet
     */
    @ApiOperation(value = "查询SyncNewData一个详情信息", notes = "查询SyncNewData一个详情信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "编码", dataType = "java.lang.String", paramType = "path")
    })
    @GetMapping(value = "/load/code/{code}")
    @ResponseBody
    public SyncNewData loadByCode(@PathVariable java.lang.String code) {
        if (code == null) {
            return null;
        }
        SyncNewData syncNewData = syncNewDataSV.loadByCode(code);
        log.info(JSON.toJSONString(syncNewData));
        return syncNewData;
    }

    /**
     * 根据条件factoryCode查询SyncNewData一个详情信息
     *
     * @param factoryCode 工厂编码
     * @return BeanRet
     */
    @ApiOperation(value = "查询SyncNewData一个详情信息", notes = "查询SyncNewData一个详情信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "factoryCode", value = "工厂编码", dataType = "java.lang.String", paramType = "path")
    })
    @GetMapping(value = "/list/factoryCode/{factoryCode}")
    @ResponseBody
    public List<SyncNewData> listByFactoryCode(@PathVariable java.lang.String factoryCode) {
        if (factoryCode == null) {
            return null;
        }
        List<SyncNewData> syncNewDataList = syncNewDataSV.listByFactoryCode(factoryCode);
        log.info(JSON.toJSONString(syncNewDataList));
        return syncNewDataList;
    }

    /**
     * 根据条件dataCode查询SyncNewData一个详情信息
     *
     * @param dataCode 数据编码
     * @return BeanRet
     */
    @ApiOperation(value = "查询SyncNewData一个详情信息", notes = "查询SyncNewData一个详情信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dataCode", value = "数据编码", dataType = "java.lang.String", paramType = "path")
    })
    @GetMapping(value = "/list/dataCode/{dataCode}")
    @ResponseBody
    public List<SyncNewData> listByDataCode(@PathVariable java.lang.String dataCode) {
        if (dataCode == null) {
            return null;
        }
        List<SyncNewData> syncNewDataList = syncNewDataSV.listByDataCode(dataCode);
        log.info(JSON.toJSONString(syncNewDataList));
        return syncNewDataList;
    }


    /**
     * 查询SyncNewData信息集合
     *
     * @return 分页对象
     */
    @ApiOperation(value = "查询SyncNewData信息集合", notes = "查询SyncNewData信息集合")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "curPage", value = "当前页", required = true, paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", required = true, paramType = "query"),
            @ApiImplicitParam(name = "id", value = "id", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "编码", paramType = "query"),
            @ApiImplicitParam(name = "factoryCode", value = "工厂编码", paramType = "query"),
            @ApiImplicitParam(name = "model", value = "模块", paramType = "query"),
            @ApiImplicitParam(name = "dataCode", value = "数据编码", paramType = "query"),
            @ApiImplicitParam(name = "ver", value = "版本", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "同步状态：禁止同步 Ban, 可同步 Ready,同步中 Sync,同步错误 Error,已经同步 Synced ", paramType = "query"),
            @ApiImplicitParam(name = "createTimeBegin", value = "创建开始时间", paramType = "query"),
            @ApiImplicitParam(name = "createTimeEnd", value = "创建结束时间", paramType = "query"),
            @ApiImplicitParam(name = "updateTimeBegin", value = "更新开始时间", paramType = "query"),
            @ApiImplicitParam(name = "updateTimeEnd", value = "更新结束时间", paramType = "query")
    })
    @PostMapping(value = "/list")
    @ResponseBody
    public List<SyncNewData> list(@RequestBody @ApiIgnore SyncNewData syncNewData, Integer curPage, Integer pageSize) {
        Page<SyncNewData> page = new Page<SyncNewData>(pageSize, curPage);
        List<SyncNewData> syncNewDatas = syncNewDataSV.list(syncNewData, page.genRowStart(), page.getPageSize());
        int total = syncNewDataSV.count(syncNewData);
        page.setTotalRow(total);
        log.info(JSON.toJSONString(page));
        return syncNewDatas;
    }


    /**
     * 查询SyncNewData信息集合
     *
     * @return 分页对象
     */
    @ApiOperation(value = "查询SyncNewData信息集合", notes = "查询SyncNewData信息集合")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "curPage", value = "当前页", required = true, paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", required = true, paramType = "query"),
            @ApiImplicitParam(name = "id", value = "id", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "编码", paramType = "query"),
            @ApiImplicitParam(name = "factoryCode", value = "工厂编码", paramType = "query"),
            @ApiImplicitParam(name = "dataCode", value = "数据编码", paramType = "query")
    })
    @GetMapping(value = "/list/by")
    @ResponseBody
    public List<SyncNewData> listByPk(java.lang.Long id, java.lang.String code, java.lang.String factoryCode, java.lang.String dataCode, Integer curPage, Integer pageSize) {
        Page<SyncNewData> page = new Page<SyncNewData>(pageSize, curPage);
        List<SyncNewData> syncNewDatas = syncNewDataSV.list(id, code, factoryCode, dataCode, page.genRowStart(), page.getPageSize());
        int total = syncNewDataSV.count(id, code, factoryCode, dataCode);
        page.setTotalRow(total);
        log.info(JSON.toJSONString(page));
        return syncNewDatas;
    }

    /**
     * 统计SyncNewData信息数量根据主键
     *
     * @return 总条数
     */
    @ApiOperation(value = " 统计SyncNewData信息数量根据主键", notes = " 统计SyncNewData信息数量根据主键")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "编码", paramType = "query"),
            @ApiImplicitParam(name = "factoryCode", value = "工厂编码", paramType = "query"),
            @ApiImplicitParam(name = "dataCode", value = "数据编码", paramType = "query")
    })
    @GetMapping(value = "/count/by")
    @ResponseBody
    public Integer count(java.lang.Long id, java.lang.String code, java.lang.String factoryCode, java.lang.String dataCode) {
        return syncNewDataSV.count(id, code, factoryCode, dataCode);
    }

    /**
     * 统计SyncNewData信息数量
     *
     * @return 总条数
     */
    @ApiOperation(value = "统计SyncNewData信息数量", notes = "统计SyncNewData信息数量")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "编码", paramType = "query"),
            @ApiImplicitParam(name = "factoryCode", value = "工厂编码", paramType = "query"),
            @ApiImplicitParam(name = "model", value = "模块", paramType = "query"),
            @ApiImplicitParam(name = "dataCode", value = "数据编码", paramType = "query"),
            @ApiImplicitParam(name = "ver", value = "版本", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "同步状态：禁止同步 Ban, 可同步 Ready,同步中 Sync,同步错误 Error,已经同步 Synced ", paramType = "query"),
            @ApiImplicitParam(name = "createTime", value = "创建时间", paramType = "query"),
            @ApiImplicitParam(name = "updateTime", value = "更新时间", paramType = "query")
    })
    @PostMapping(value = "/count")
    @ResponseBody
    public Integer count(@RequestBody SyncNewData syncNewData) {
        return syncNewDataSV.count(syncNewData);
    }


    /**
     * 创建SyncNewData
     *
     * @return BeanRet
     */
    @ApiOperation(value = "创建SyncNewData", notes = "创建SyncNewData")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "model", value = "模块", paramType = "query"),
            @ApiImplicitParam(name = "ver", value = "版本", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "同步状态：禁止同步 Ban, 可同步 Ready,同步中 Sync,同步错误 Error,已经同步 Synced ", paramType = "query"),
    })
    @PostMapping("/build")
    @ResponseBody
    public SyncNewData build(@RequestBody @ApiIgnore SyncNewData syncNewData) {
        syncNewDataSV.save(syncNewData);
        return syncNewData;
    }


    /**
     * 修改SyncNewData
     *
     * @return BeanRet
     */
    @ApiOperation(value = "修改SyncNewData", notes = "修改SyncNewData")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "编码", paramType = "query"),
            @ApiImplicitParam(name = "factoryCode", value = "工厂编码", paramType = "query"),
            @ApiImplicitParam(name = "model", value = "模块", paramType = "query"),
            @ApiImplicitParam(name = "dataCode", value = "数据编码", paramType = "query"),
            @ApiImplicitParam(name = "ver", value = "版本", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "同步状态：禁止同步 Ban, 可同步 Ready,同步中 Sync,同步错误 Error,已经同步 Synced ", paramType = "query"),
            @ApiImplicitParam(name = "createTime", value = "创建时间", paramType = "query"),
            @ApiImplicitParam(name = "updateTime", value = "更新时间", paramType = "query")
    })
    @PutMapping("/modify")
    @ResponseBody
    public SyncNewData modify(@RequestBody @ApiIgnore SyncNewData syncNewData) {
        syncNewDataSV.modify(syncNewData);
        return syncNewData;
    }

    /**
     * 删除SyncNewData
     *
     * @return BeanRet
     */
    @ApiOperation(value = "删除SyncNewData", notes = "删除SyncNewData")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "编码", paramType = "query"),
            @ApiImplicitParam(name = "factoryCode", value = "工厂编码", paramType = "query"),
            @ApiImplicitParam(name = "dataCode", value = "数据编码", paramType = "query")
    })
    @DeleteMapping("/delete")
    @ResponseBody
    public BeanRet delete(java.lang.Long id, java.lang.String code, java.lang.String factoryCode, java.lang.String dataCode) {
        syncNewDataSV.delete(id, code, factoryCode, dataCode);
        return BeanRet.create(true, "删除SyncNewData成功");
    }

    /**
     * 从云端往工厂端同步数据调度接口
     *
     * @param param
     * @return BeanRet
     */
    @ApiOperation(value = "从云端往工厂端同步数据调度接口", notes = "从云端往工厂端同步数据调度接口")
    @ApiImplicitParam(name = "factoryCode", value = "factoryCode", dataType = "String", required = true, paramType = "query")
    @RequestMapping(value = "/syncDataToDown", method = RequestMethod.POST)
    @ResponseBody
    public BeanRet syncDataToDown(@RequestBody String param) throws Exception {
        Map<String, Object> paraMap = JSON.parseObject(param);
        if (paraMap.get("thresHold") == null) {
            return syncNewDataSV.syncDataToDown(paraMap.get("factoryCode").toString(), null);
        }
        Long thresHoldTime = (Long) paraMap.get("thresHold");
        Date thresHold = new Date(thresHoldTime);
        return syncNewDataSV.syncDataToDown(paraMap.get("factoryCode").toString(), thresHold);
    }


    /**
     * 获取工厂端数据同步结果
     */
    @ApiOperation(value = "获取工厂端数据同步结果", notes = "获取工厂端数据同步结果")
    @ApiImplicitParam(name = "syncResult", value = "syncResult", dataType = "String", required = true, paramType = "query")
    @RequestMapping(value = "/updateStateBySyncResult", method = RequestMethod.POST)
    @ResponseBody
    public BeanRet updateStateBySyncResult(@RequestBody String syncResult) {
        if (StringUtils.isNotBlank(syncResult)) {
            BeanRet beanRet = JSON.parseObject(syncResult, BeanRet.class);
            List<SyncNewData> syncNewDataList = JSON.parseArray(JSON.toJSONString(beanRet.getData()), SyncNewData.class);
            boolean syncDataFlag = beanRet.isSuccess();
            if (syncNewDataList == null || syncNewDataList.size() <= 0) {
                return BeanRet.create(false, BaseException.BaseExceptionEnum.Illegal_Param);
            }
            syncNewDataSV.updateStateBySyncResult(syncDataFlag, syncNewDataList);
            if (syncDataFlag) {
                return BeanRet.create(syncDataFlag, "状态更新成功");
            } else {
                return BeanRet.create(syncDataFlag, "数据同步失败");
            }
        }
        return BeanRet.create(false, BaseException.BaseExceptionEnum.Empty_Param);
    }

}
